import 'package:dio/dio.dart';
import 'package:mall/core/models/me.dart';
import 'package:mall/core/services/auth.dart';
import 'package:mall/core/providers/view_model.dart';

class UserMobileUpdateModel extends ViewModel {
  final Auth auth;
  final Me me;
  String checkCode; // 新手机号码的验证码
  String mobile; // 要绑定的新手机号码
  String verifyCode; // 原手机验证码
  String _errorMessage;

  UserMobileUpdateModel(this.auth, this.me) : super();

  String get errorMessage => _errorMessage;

  Future<ViewState> userMobileUpdate() async {
    viewState = ViewState.busy;
    try {
      if (mobile == null || mobile.isEmpty) {
        throw '请输入要绑定的新手机号码';
      }
      if (checkCode == null || checkCode.isEmpty) {
        throw '请输入新手机接收的验证码';
      }
      if (me.mobile != null) {
        if (verifyCode == null || verifyCode.isEmpty) {
          throw '请输入原手机接收的验证码';
        }
      }
      var params = <String, dynamic>{};
      params['mobile'] = mobile;
      params['checkCode'] = checkCode;
      params['verifyCode'] = verifyCode;
      await auth.userMobileUpdate(params);
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }
}
